package com.ruoyi.app.business.file;

import cn.hutool.json.JSONUtil;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.domain.common.UploadResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.service.file.entity.FileContentEntity;
import com.ruoyi.service.file.service.FileContentService;
import com.ruoyi.service.user.model.UserInfoModel;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 作用：文件内容读取器
 * </p>
 *
 * @author Zane
 * @since 2025-10-10 1:34
 */
@Slf4j
@Component
public class FileBusiness {

  @Resource
  private RemoteFileService remoteFileService;
  @Resource
  private FileContentService fileContentService;

  public FileContentEntity saveFileContent(String fileName, String fileUrl, String contentJson) {
    return saveFileContent(fileName, fileUrl, contentJson, UserUtil.getUserId());
  }

  public FileContentEntity saveFileContent(String fileName, String fileUrl, String contentJson,
      Long userId) {
    return fileContentService.saveFileContent(fileName, fileUrl, contentJson, userId);
  }


  public Map<String, FileContentEntity> mapByFileKeys(List<String> fileKeys) {
    return Optional.ofNullable(listByFileKeys(fileKeys)).orElseGet(ArrayList::new)
        .stream().collect(Collectors.toMap(FileContentEntity::getFileKey, v -> v
            , (v1, v2) -> v1));
  }

  public List<FileContentEntity> listByFileKeys(List<String> fileKeys) {
    //
    return fileContentService.listByFileKeys(fileKeys);
  }

  public FileContentEntity selectByFileKey(String fileKey) {
    //
    return fileContentService.selectByFileKey(fileKey);
  }

  public <T> List<T> dataListByFileKey(String fileKey, Class<T> clazz) {
    final FileContentEntity entity = selectByFileKey(fileKey);
    return JSONUtil.toList(entity.getFileData(), clazz);
  }

  public <T> T dataObjectByFileKey(String fileKey, Class<T> clazz) {
    final FileContentEntity entity = selectByFileKey(fileKey);
    return JSONUtil.toBean(entity.getFileData(), clazz);
  }

  public UploadResult upload(MultipartFile file, boolean keepName) {
    if (!file.isEmpty()) {
      //final String extension = FileTypeUtils.getExtension(file);
//      if (!extension.equals("pdf")) {
//        throw new ServiceException("文件格式不正确，请上传pdf格式");
//      }
      final R<SysFile> fileResult = remoteUpload(file, keepName);
      if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
        throw new ServiceException("文件服务异常，请联系管理员");
      }
      final String url = fileResult.getData().getUrl();
      final String fileName = file.getOriginalFilename();
      final FileContentEntity entity = this.saveFileContent(fileName, url,
          JSONUtil.toJsonStr(new Object()), Optional.ofNullable(UserUtil.getLoginUserMayBeNull())
              .orElseGet(() -> new UserInfoModel().setUserId(-9999999L)).getUserId());
      UploadResult uploadResult = new UploadResult();
      uploadResult.setFileUrl(url);
      uploadResult.setFileKey(entity.getFileKey());
      uploadResult.setFileName(fileName);
      return uploadResult;
    }
    return null;
  }

  public R<SysFile> remoteUpload(MultipartFile file, boolean keepName) {
    if (keepName) {
      return remoteFileService.uploadKeepName(file);
    }
    return remoteFileService.upload(file);
  }
}
